import {
    getUploadApi,
    getVisitorInfoApi,
    loginApi,
    setMsgReadApi
} from '@/api/user/user'
import { LoginParam, SendMessage } from '@/api/user/UserModel'
import { StatusCode } from '@/http/request'
import { custCareUserStore } from '@/store/custcare'
import { messageStore } from '@/store/messages'
import { IMessage } from '@/store/type'
import { MESSAGE_CMD, MESSAGE_TYPE } from '@/types/CustcareEnum'
import {
    cleanSession,
    getExpireTime,
    getToken,
    getUserInfo,
    setExpireTime,
    setToken,
    setUserInfo
} from '@/utils/auth'
import {
    formatDateHms,
    getNowTime,
    getNowTimeText,
    getParam
} from '@/utils/filters'
import { getLocalStorage, setLocalStorage } from '@/utils/localStore'
import { alertMsg } from '@/utils/utils'
import { computed, nextTick, onMounted, reactive, ref } from 'vue'

export default function useBase() {
    const custStore = custCareUserStore()
    const mStore = messageStore()
    let checkLastSendMsgTime: any

    const baseURL = <string>import.meta.env.VITE_CUSTCARE_IMG_SERVER
    const msg = ref('')
    const isShowEmo = ref(false)
    const imgFileInput = ref<InstanceType<typeof HTMLInputElement>>()
    const dialogCloseTime = ref(600000)
    const isCanSend = ref(true)
    const isShowImg = ref(false)
    const showImgSrc = ref('/src/assets/icons/image-line.svg')
    let unreadRemindTime: any
    let unreadRemindCount = ref(0)
    const IsMobile = ref(false)

    const headTitle = ref('')
    const headLogo = ref('')

    const emos = ref([
        'amazed-face',
        'amusing-face',
        'anguished-face',
        'astonished-face',
        'backhand-index-pointing-down-1',
        'backhand-index-pointing-up-1',
        'beaming-face-with-smiling-eyes',
        'clapping-hands-1',
        'confounded-face',
        'crazy-face',
        'crying-face',
        'determined-face',
        'downcast-face-with-sweat',
        'drooling-face-1',
        'drooling-face-2',
        'face-blowing-a-kiss',
        'face-savoring-food',
        'face-screaming-in-fear',
        'face-vomiting',
        'face-with-head-bandage',
        'face-with-medical-mask',
        'face-with-monocle',
        'face-with-steam-from-nose',
        'face-with-symbols-on-mouth',
        'face-with-tears-of-joy',
        'face-with-tongue',
        'fearful-face',
        'flexed-biceps-1',
        'folded-hands-1',
        'frowning-face',
        'grimacing-face',
        'grinning-face',
        'grinning-face-with-smiling-eyes',
        'grinning-face-with-sweat',
        'grinning-squinting-face',
        'hushed-face-2',
        'index-pointing-up-1',
        'kissing-face-with-closed-eyes',
        'kissing-face-with-smiling-eyes',
        'loudly-crying-face',
        'money-mouth-face-1',
        'nauseated-face-2',
        'nerd-face',
        'ok-hand-1',
        'oncoming-fist-1',
        'persevering-face',
        'pouting-face',
        'raised-fist-1',
        'raised-hand-1',
        'shushing-face',
        'sleeping-face',
        'sleepy-face',
        'smiling-face-with-heart-eyes',
        'smiling-face-with-smiling-eyes',
        'smiling-face-with-sunglasses',
        'sneezing-face',
        'squinting-face-with-tongue',
        'star-struck-1',
        'star-struck-2',
        'thumbs-down-1',
        'thumbs-up-1',
        'victory-hand-1',
        'waving-hand-1'
    ])

    const messageList = computed(() => {
        return mStore.getMessages
    })

    const getOnMessage = (e: any) => {
        const msg = JSON.parse(e.detail.data)
        // console.log('收到消息: ', msg)
        if (msg.cmd == MESSAGE_CMD.CMD_HEART) {
            console.log('心跳: ' + msg.content)
            return
        }
        const userInfo = getUserInfo()
        if (userInfo != null) {
            if (msg.type == MESSAGE_TYPE.TYPE_NOTIFY_REPLACE_SERVICE) {
                console.log('转接到新的客服')
                getVisitorInfo()
            } else {
                clearInterval(unreadRemindTime)
                unreadRemindTime = setInterval(() => {
                    let title = headTitle.value
                    if (unreadRemindCount.value % 2 == 0) {
                        title = '[new message]' + title
                    }
                    if (IsMobile.value) {
                        document.title = title
                    } else {
                        window.parent.postMessage(title, '*')
                    }

                    unreadRemindCount.value++
                }, 1000)

                const iMessage = reactive<IMessage>({
                    msg_type: 'left', // left / right
                    uuid: userInfo.service_uuid,
                    nickname: userInfo.service_name,
                    avatar: userInfo.service_avatar,
                    client_ip: '',
                    type: msg.type,
                    content: msg.content,
                    send_time: msg.send_time,
                    send_time_text: formatDateHms(msg.send_time),
                    children: msg.children
                })
                mStore.addMessage(iMessage)
                if (iMessage.type <= 3) {
                    setMsgRead()
                }
                setScrollTop()
            }
        }
    }

    const login = async () => {
        const loginModel = reactive<LoginParam>({
            sys_uuid: ''
        })
        const res = await loginApi(loginModel)
        console.log('登录结果：', res)
        if (res.code == StatusCode.Success) {
            setToken(res.data.access_token)
            setExpireTime(res.data.access_expire)
            getVisitorInfo()
        } else {
            alertMsg(res.msg)
        }
    }

    const getOnClose = (e: any) => {
        // 监听关闭
        console.log('关闭了', e)
        clearInterval(checkLastSendMsgTime)
    }

    const getOnHeartBeat = () => {
        const userInfo = getUserInfo()
        if (userInfo) {
            const msg = reactive<SendMessage>({
                cmd: MESSAGE_CMD.CMD_HEART,
                channel_id: userInfo.channel_id,
                to_user_uuid: userInfo.service_uuid,
                type: MESSAGE_TYPE.TYPE_TEXT,
                content: 'ping'
            })
            custStore.getSocket.sendMessage(msg)
        }
    }

    const goSocket = () => {
        window.addEventListener('onMessageWS', getOnMessage)
        window.addEventListener('onCloseWS', getOnClose)
        window.addEventListener('onHeartBeatWs', getOnHeartBeat)
        repeatConnectSocket()
        setMsgRead()
    }

    const repeatConnectSocket = () => {
        custStore.setSocket()
        setLastSendMsgTime()
        clearInterval(checkLastSendMsgTime)
        checkLastSendMsgTime = setInterval(() => {
            console.log(
                '距离上次发消息多久=',
                getLocalStorage('lastSendMsgTime')
            )
            const lastTime = getLocalStorage('lastSendMsgTime')
            if (lastTime != null) {
                const lastTimeInt = parseInt(lastTime)
                const nowTime = Date.now()
                // 和最后一次发送消息时间间隔
                const intervalTime = nowTime - lastTimeInt
                if (intervalTime > dialogCloseTime.value) {
                    custStore.getSocket.wsClose()
                    isCanSend.value = false
                }
            }
        }, 10000)

        isCanSend.value = true
    }

    const handleSend = () => {
        const content = msg.value
        if (!content) {
            alertMsg('请输入内容！')
            return
        }
        sendMsg(MESSAGE_TYPE.TYPE_TEXT, content)

        msg.value = ''
    }

    const setLastSendMsgTime = () => {
        // 记录最后一次发送消息时间
        const nowTime = Date.now()
        setLocalStorage('lastSendMsgTime', JSON.stringify(nowTime))
    }

    const sendMsg = (type: number, content: string) => {
        if (custStore.getSocket.instance) {
            const userInfo = getUserInfo()
            if (userInfo) {
                setLastSendMsgTime()
                const msg = reactive<SendMessage>({
                    cmd: MESSAGE_CMD.CMD_MSG,
                    channel_id: userInfo.channel_id,
                    to_user_uuid: userInfo.service_uuid,
                    type: type,
                    content: content
                })
                custStore.getSocket.sendMessage(msg)
                const iMessage = reactive<IMessage>({
                    msg_type: 'right', // left / right
                    uuid: userInfo.uuid,
                    nickname: userInfo.nickname,
                    avatar: userInfo.avatar,
                    client_ip: userInfo.client_ip,
                    type: type,
                    content: content,
                    send_time: getNowTime(),
                    send_time_text: getNowTimeText(),
                    children: null
                })
                mStore.addMessage(iMessage)
                setScrollTop()
            }
        }
    }

    const setScrollTop = () => {
        setTimeout(() => {
            let list = document.querySelector('#messageList')
            if (list != null) {
                // list.scrollTop = list.scrollHeight
                list.scrollTo(0, list.scrollHeight)
            }
        }, 200)
    }

    const showEmo = () => {
        isShowEmo.value = !isShowEmo.value
    }

    const handleEmo = (emo: string) => {
        isShowEmo.value = false
        msg.value = msg.value + ':' + emo + ':'
    }

    const emotion = (res: string) => {
        let word = res.replace(/\:/gi, '')
        return `<img class="emotion" src="/src/assets/emo/streamlinehq-${word}-smiley-people-102.png">`
    }

    const handleImgFileChange = async (e: Event) => {
        const target = e.target as HTMLInputElement
        // console.log(target.files)
        if (target.files) {
            const files = Array.from(target.files)
            console.log('files=', files)
            if (files.length > 0) {
                // 取得文件
                const uploadedFile = files[0]
                console.log('uploadedFile=', uploadedFile)
                if (
                    uploadedFile.type == 'image/jpeg' ||
                    uploadedFile.type == 'image/png' ||
                    uploadedFile.type == 'image/gif'
                ) {
                    if (uploadedFile.size / 1024 / 1024 > 4) {
                        alertMsg('图片大小不能超过4MB！')
                        return false
                    }

                    const formData = new FormData()
                    formData.append('file', uploadedFile)

                    const res = await getUploadApi(formData)
                    console.log('上传结果', res)
                    if (res.code == StatusCode.Success) {
                        // 发送图片地址
                        sendMsg(MESSAGE_TYPE.TYPE_IMG, res.data.path)
                    } else {
                        alertMsg(res.msg)
                    }

                    return true
                } else {
                    alertMsg('必须是JPG、PNG格式的图片！')
                    return false
                }
            }
        }
    }

    const clickUploadImg = () => {
        imgFileInput.value?.click()
    }

    const handleShowImg = (imgSrc: string) => {
        showImgSrc.value = imgSrc
        isShowImg.value = true
    }

    const closeChat = () => {
        if (IsMobile.value) {
            window.history.go(-1)
        } else {
            window.parent.postMessage('close', '*')
        }
    }

    // 设置成已读
    const setMsgRead = async () => {
        let res = await setMsgReadApi()
        if (res && res.code == StatusCode.Success) {
            console.log(res.data)
        } else {
            console.log(res)
        }
    }

    const getVisitorInfo = async () => {
        const userRes = await getVisitorInfoApi()
        console.log('userRes=', userRes)
        if (userRes) {
            if (userRes.code == StatusCode.Success) {
                setUserInfo(JSON.stringify(userRes.data))
                // ws连接
                setTimeout(() => {
                    goSocket()
                }, 1000)
                setScrollTop()
            } else {
                alertMsg(userRes.msg)
            }
        } else {
            alertMsg('获得用户信息失败！')
        }
    }

    const handleReply = (content: string) => {
        // 问问题
        const type = MESSAGE_TYPE.TYPE_ASK_QUESTION
        if (custStore.getSocket.instance) {
            const userInfo = getUserInfo()
            if (userInfo) {
                setLastSendMsgTime()
                const msg = reactive<SendMessage>({
                    cmd: MESSAGE_CMD.CMD_MSG,
                    channel_id: userInfo.channel_id,
                    to_user_uuid: userInfo.service_uuid,
                    type: type,
                    content: content
                })
                custStore.getSocket.sendMessage(msg)
                const iMessage = reactive<IMessage>({
                    msg_type: 'right', // left / right
                    uuid: userInfo.uuid,
                    nickname: userInfo.nickname,
                    avatar: userInfo.avatar,
                    client_ip: userInfo.client_ip,
                    type: type,
                    content: content,
                    send_time: getNowTime(),
                    send_time_text: getNowTimeText(),
                    children: null
                })
                mStore.addMessage(iMessage)
                setScrollTop()
            }
        }
    }

    const clickContent = () => {
        console.log('光标定位: ' + headTitle.value)
        // console.log(window.parent)
        if (IsMobile.value) {
            document.title = headTitle.value
        } else {
            window.parent.postMessage(headTitle.value, '*')
        }
        clearInterval(unreadRemindTime)
    }

    const getMobile = () => {
        let info = navigator.userAgent
        let agents = [
            'Android',
            'iPhone',
            'SymbianOS',
            'Windows Phone',
            'iPod',
            'iPad'
        ]
        for (let i = 0; i < agents.length; i++) {
            if (info.indexOf(agents[i]) >= 0) return true
        }
        return false
    }

    onMounted(async () => {
        if (getMobile()) {
            IsMobile.value = true
        }
        //获取token
        const token = getToken()
        const expireTime = getExpireTime()
        if (token != null && expireTime != null) {
            console.log('已登录')
            const expireTimeInt = parseInt(expireTime) * 1000
            const nowTime = Date.now()
            console.log('过期时间=', expireTimeInt)
            console.log('现在时间=', nowTime)
            if (expireTimeInt > nowTime) {
                getVisitorInfo()
            } else {
                // 过期重新登录
                cleanSession()
                login()
            }
        } else {
            console.log('未登录')
            login()
        }

        nextTick(() => {
            headTitle.value = decodeURI(getParam('head_title'))
            headLogo.value = getParam('head_logo')
        })
    })

    return {
        headTitle,
        headLogo,
        msg,
        isShowEmo,
        imgFileInput,
        emos,
        messageList,
        handleSend,
        showEmo,
        handleEmo,
        emotion,
        handleImgFileChange,
        clickUploadImg,
        isCanSend,
        repeatConnectSocket,
        isShowImg,
        showImgSrc,
        handleShowImg,
        closeChat,
        handleReply,
        clickContent
    }
}
